<?php
/**
 * Created by PhpStorm.
 * User: Keter
 * Date: 2016/9/8
 * Time: 21:42
 */
class PayLogQueen extends StatsLogBase
{
      public $baseTableName = 'log_pay';
      public $mainTableName = 'log_pay_stats';

    /**
     * 保存到数据库
     * @param $data
     * @return array
     */
    public function saveLog($data)
    {
        /**
         * 保存数据
         */
        $where = [
            'serverID' => $data['serverID'],
            'roomID' => $data['roomID'],
            'dieTime' => $data['dieTime']
        ];

        $result = $this->mysql('logs')->findRow($this->tableName, $where, 'serverID');
        if ($result) {
            $this->e('pay log: exists_record', $where);
            return false;
        }

        $detail = json_decode($data['allTotalScore'], JSON_UNESCAPED_UNICODE);
        $saveData = [
            'serverID' => $data['serverID'],
            'roomID' => $data['roomID'],
            'dieTime' => $data['dieTime'],
            'isPay' => 0,
            'deductTime' => $data['deductTime'],
            'roomCreator' => $data['roomCreator'],
            'totalRound' => $data['totalRound'],
            'realRound' => $data['realRound'],
            'diamond' => $data['diamond'],
        ];

        foreach ($detail as $key => $row) {
            $index = $key + 1;
            if ($index < 4) {
                $saveData['uid' . $index] = $row['uid'];
                $saveData['score' . $index] = $row['score'];
                $saveData['seat' . $index] = $row['seat'];
            }
        }

        $result = $this->mysql('logs')->insert($this->tableName, $saveData);
        if (!$result) {
            $this->e('save_error', $this->mysql('logs')->error());
            $this->e('赔付日志保存失败', $saveData);
            return false;
        }

        /**
         * 统计数据
         */
        $where = [
            'serverID' => $saveData['serverID'],
            'dieTime' => $saveData['dieTime']
        ];
        $fields = "COUNT(DISTINCT roomCreator) AS totalUser,
                   COUNT(DISTINCT roomID) AS totalRoom,
                   SUM(diamond) AS totalDiamond";
        $result = $this->mysql('logs')->findRow($this->tableName, $where, $fields);
        if ($result) {
            $row = $this->mysql('logs')->findRow($this->mainTableName, $where);
            if ($row) {
                $saveData = $result;
                $saveData['totalDiamond'] = 0;
                $this->mysql('logs')->update($this->mainTableName, $where, $saveData);
            } else {
                $saveData = array_merge($where, $result);
                $saveData['totalDiamond'] = 0;
                $this->mysql('logs')->insert($this->mainTableName, $saveData, true);
            }
        }

        return $data;
    }
}